package com.kun.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.kun.config.EntityRedisSerializer;
import com.kun.entity.User;
import com.kun.service.UserService;
import com.kun.util.GenerateRandomNumber;

@Controller
public class SendEmailController {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private UserService userServiceImpl;
	
	@Autowired
    private JavaMailSender mailSender;

	@Autowired
    protected RedisTemplate<String, Object> redisTemplate;
	
	@Autowired  
	DefaultKaptcha defaultKaptcha; 
	
    @Value("${mail.fromMail.addr}")
    private String from;
    
    final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
    
    /**
     * 发送注册验证码邮件
     * @param to
     */
    @RequestMapping(value = "/sendEmailForReg",method=RequestMethod.POST)
    @ResponseBody
    public String sendCodeToMail(@RequestParam("email") String to,HttpServletResponse httpServletResponse) {
    	String msg = "";
    	if(!Pattern.matches(REGEX_EMAIL, to)){
    		return "邮箱格式不正确";
    	}
    	User user = userServiceImpl.selectUserByLogUsername(to);
    	if(user!=null){
    		return "用户已存在";
    	}
        String createText = defaultKaptcha.createText();
        String content = "您好,你正在Charity Book上注册账号,请使用下面的验证码验证您的操作，验证码 10 分钟内有效:" + createText;
        System.out.println(content);
        String uuid = UUID.randomUUID().toString();
        Cookie cookie = new Cookie("CaptchaCode",uuid);
        try {
        	MimeMessage mimeMessage = mailSender.createMimeMessage();  
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);  
        	helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject("Charity Book 账号注册！");
            helper.setText(content);
            
            //uuid是redis的key
            redisTemplate.setValueSerializer(new EntityRedisSerializer());
            redisTemplate.opsForValue().set(uuid, createText, 10*60, TimeUnit.SECONDS);
            //把redis的key保存到cookie
            cookie.setPath("/");//踩坑
            logger.info(cookie.getValue());
            httpServletResponse.addCookie(cookie);
            
            mailSender.send(mimeMessage);
            msg = "注册验证邮件已经发送";
            logger.info(msg);
        } catch (Exception e) {
        	msg = "发送注册邮件时发生异常！";
        	if(redisTemplate.hasKey(uuid)){//回滚
        		redisTemplate.delete(uuid);//删除redis key
        		cookie.setPath("/");
        		cookie.setMaxAge(0);
                httpServletResponse.addCookie(cookie);
        	}
            logger.error(msg, e);
        }
        return msg;
    }
    
    /**
     * 校验注册邮箱验证码
     * */
    @RequestMapping("/validateEmailCode")
    @ResponseBody
    public String validateEmailCode(@RequestParam(name="inputCode") String inputCode,HttpServletRequest httpServletRequest){
    	Cookie[] c = httpServletRequest.getCookies();
    	String uuid = "";
    	String msg = "";
    	for(int i=0;i<c.length;i++){
    		Cookie cookie = c[i];
    		if("CaptchaCode".equals(cookie.getName())){
    			uuid = cookie.getValue();
    		}
    	}
    	if(!"".equals(uuid)){
    		redisTemplate.setValueSerializer(new EntityRedisSerializer());
    		String validateCode =  (String) redisTemplate.opsForValue().get(uuid);
        	if(inputCode.toLowerCase().equals(validateCode)){
        		msg = "true";
        	}else{
        		msg = "false";
        	}
        	logger.info(validateCode+"-"+inputCode.toLowerCase()+"-"+msg);
    	}
    	return msg;
    }
    
    
    /**
     * 发送找回密码邮件
     * @param to
     */
    @RequestMapping(value = "/findpassword",method=RequestMethod.POST)
    @ResponseBody
    public String sendUrlToMail(@RequestParam("email") String to,HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse) {
    	if(!Pattern.matches(REGEX_EMAIL, to)){
    		return "邮箱格式不正确";
    	}
    	User user = userServiceImpl.selectUserByLogUsername(to);
    	if(user==null){
    		return "邮箱未注册";
    	}
    	String msg = "";
        String token = GenerateRandomNumber.getCharAndNumr(20);
        String url = httpServletRequest.getRequestURL().toString();//地址栏路径
        String uri = httpServletRequest.getRequestURI();//相对工程路径
        url = url.replaceAll(uri, "");
        String html = url + "/resetPassword?email="+to+"&token=" + token;
        String uuid = UUID.randomUUID().toString();
        Cookie cookie = new Cookie("tokenMap",uuid);
        try {
        	MimeMessage mimeMessage = mailSender.createMimeMessage();  
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true,"gbk");  
        	helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject("Charity Book 密码找回！");
            helper.setText("<html>亲爱的用户" + to + "，您好！"+"</br>"
			 		+ "您在" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + "提交找回密码的请求。可以点击下面的链接来重置密码。</br>"
			 		+ html+"</br>"
			 		+ "请您尽快修改密码，感谢使用本系统。" + "</br>"
			 		+ "此为自动发送邮件，请勿直接回复！</html>",true);
            
            //添加验证码到cookie
            Map<String,String> map = new HashMap<String,String>();
            map.put(to, token);
            //uuid是redis的key
            redisTemplate.setValueSerializer(new EntityRedisSerializer());
            redisTemplate.opsForValue().set(uuid, map, 10*60, TimeUnit.SECONDS);
            //把redis的key保存到cookie
            cookie.setPath("/");
            logger.info(cookie.getValue());
            httpServletResponse.addCookie(cookie);
            
            mailSender.send(mimeMessage);
            msg = "重置密码邮件已发送，请按邮件提示重置密码";
            logger.info(msg);
        } catch (Exception e) {
        	msg = "发送重置密码邮件时发生异常！";
        	if(redisTemplate.hasKey(uuid)){//回滚
        		redisTemplate.delete(uuid);//删除redis key
        		cookie.setPath("/");
        		cookie.setMaxAge(0);
                httpServletResponse.addCookie(cookie);
        	}
            logger.error(msg, e);
        }
        return msg;
    }

}
